package com.meeruu.sg.account.core.domain.component.lock;

import com.meeruu.boot.ucs.annotation.NamedCache;
import com.meeruu.boot.ucs.datasource.redis.IRedisCache;
import com.meeruu.sg.account.core.api.exception.AccountException;
import com.meeruu.sg.account.core.api.exception.ErrorCode;
import org.springframework.stereotype.Service;


/**
 * @Auther: liwu
 * @Date: 2019/4/18 10:01
 * @Description:
 */
@Service
public class LockTemplate {

    @NamedCache("default")
    private IRedisCache ucsCache;

    public <T> T execute(BizLock bizLock, LockCallback<T> lockCallback) throws AccountException {

        if (!ucsCache.lock(bizLock.getLockKey(), bizLock.getExpire())) {

            throw new AccountException(ErrorCode.BIZ_EXEC_FLEQUENT.getCode(), bizLock.toString() + "业务正在处理中。。。,请勿频繁提交");
        }
        try {
            //处理业务逻辑
            return lockCallback.invoke();

        } finally {
            ucsCache.unlock(bizLock.getLockKey());
        }
    }


}
